<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

// 配置axios实例
const apiClient = axios.create({
  baseURL: 'https://api-cn.freatz.com',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  },
  // 启用跨域凭证
  withCredentials: true,
  // 在开发环境中允许自签名证书
  httpsAgent: process.env.NODE_ENV === 'development' ? {
    rejectUnauthorized: false
  } : undefined
})

// 提取cookie中特定名称的值的函数
function getCookie(name) {
  const cookieValue = document.cookie
    .split('; ')  // 分割cookie字符串
    .find(row => row.startsWith(name + '='))  // 查找指定名称的cookie
    ?.split('=')[1]  // 提取值
  return cookieValue ? decodeURIComponent(cookieValue) : null
}

// 提取CSRFToken的函数
function getCSRFToken() {
  return getCookie('X-CSRFToken') || 
         getCookie('XSRF-TOKEN') || 
         document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ||
         null
}

// 响应数据状态
const responseData = ref(null)
const loading = ref(false)
const error = ref(null)

// 发送请求的函数
const sendRequest = async () => {
  loading.value = true
  error.value = null
  responseData.value = null
  
  try {
    // 提前获取CSRFToken进行调试
    const csrfToken = getCSRFToken()
    console.log('CSRFToken before request:', csrfToken)
    
    // 详细记录当前所有cookie
    const allCookies = document.cookie
    console.log('All cookies before request:', allCookies)
    
    // 解析cookies为对象以便更好地检查
    const parsedCookies = {}
    document.cookie.split('; ').forEach(cookie => {
      const [name, value] = cookie.split('=')
      parsedCookies[name] = decodeURIComponent(value)
    })
    console.log('Parsed cookies before request:', parsedCookies)
    
    // 手动设置CSRF头
    const requestConfig = {
      withCredentials: true,
      withXSRFToken: true,
      xsrfHeaderName: 'X-CSRFToken',
      headers: {}
    }
    
    // 如果找到CSRFToken，手动添加到请求头
    // if (csrfToken) {
    //   requestConfig.headers['X-CSRFToken'] = csrfToken
    //   console.log('Added CSRFToken to request headers:', csrfToken)
    // }
    
    // 使用配置好的apiClient发送POST请求
    const response = await apiClient.post('/v1/users/auth/login/', {
      email: 'freatz+test@freatz.com',
      password: 'test1234'
    }, requestConfig)
   
    // 获取响应头信息
    const headers = { ...response.headers }
    
    // 获取响应体
    const body = response.data
    console.log("=======>>", response.cookies)
    // 请求后再次获取cookie信息进行对比
    const cookiesAfter = document.cookie
    console.log('All cookies after request:', cookiesAfter)
    
    // 再次解析cookies
    const parsedCookiesAfter = {}
    cookiesAfter.split('; ').forEach(cookie => {
      const [name, value] = cookie.split('=')
      console.log(`Cookie====>> ${name} = ${value}`)
      parsedCookiesAfter[name] = decodeURIComponent(value)
    })
    console.log('Parsed cookies after request:', parsedCookiesAfter)
    
    // 专门检查csrftoken
    const csrfTokenAfter = getCookie('csrftoken')
    console.log('CSRFToken after request:', csrfTokenAfter)
    
    // 保存响应数据，添加更多详细信息
    responseData.value = {
      headers,
      cookies: cookiesAfter,
      parsedCookies: parsedCookiesAfter,
      csrfToken: csrfTokenAfter,
      body
    }
  } catch (err) {
    error.value = err.message || '请求失败'
    console.error('Request error:', err)
    // 记录错误时的cookie状态
    console.error('Cookies at error time:', document.cookie)
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="container">
    <h1>HTTP请求演示</h1>
    
    <button 
      @click="sendRequest" 
      :disabled="loading"
      class="request-button"
    >
      {{ loading ? '发送中...' : '发送POST请求' }}
    </button>
    
    <div v-if="error" class="error-message">
      错误: {{ error }}
    </div>
    
    <div v-if="responseData" class="response-container">
      <h2>响应信息</h2>
      
      <div class="response-section">
        <h3>响应头 (Headers)</h3>
        <pre>{{ JSON.stringify(responseData.headers, null, 2) }}</pre>
      </div>
      
      <div class="response-section">
        <h3>Cookie 信息</h3>
        <pre>{{ responseData.cookies || '无Cookie' }}</pre>
      </div>
      
      <div class="response-section">
        <h3>解析后的Cookie</h3>
        <pre>{{ JSON.stringify(responseData.parsedCookies, null, 2) }}</pre>
      </div>
      
      <div class="response-section">
        <h3>CSRFToken</h3>
        <pre>{{ responseData.csrfToken || '未找到CSRFToken' }}</pre>
      </div>
      
      <div class="response-section">
        <h3>响应体 (Body)</h3>
        <pre>{{ JSON.stringify(responseData.body, null, 2) }}</pre>
      </div>
    </div>
  </div>
</template>

<style>
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
  line-height: 1.6;
  color: #333;
  background-color: #f5f5f5;
}

.container {
  max-width: 900px;
  margin: 0 auto;
  padding: 2rem;
}

h1 {
  text-align: center;
  margin-bottom: 2rem;
  color: #2c3e50;
}

.request-button {
  display: block;
  margin: 0 auto 2rem;
  padding: 0.75rem 2rem;
  font-size: 1rem;
  font-weight: 600;
  color: white;
  background-color: #3498db;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.request-button:hover:not(:disabled) {
  background-color: #2980b9;
}

.request-button:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
}

.error-message {
  padding: 1rem;
  background-color: #ffecec;
  color: #e74c3c;
  border-radius: 4px;
  margin-bottom: 1.5rem;
}

.response-container {
  margin-top: 2rem;
}

.response-section {
  background-color: white;
  padding: 1.5rem;
  margin-bottom: 1.5rem;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

h2 {
  margin-bottom: 1.5rem;
  color: #34495e;
}

h3 {
  margin-bottom: 1rem;
  color: #7f8c8d;
  font-size: 1rem;
}

pre {
  background-color: #f8f9fa;
  padding: 1rem;
  border-radius: 4px;
  overflow-x: auto;
  font-family: 'Courier New', Courier, monospace;
  font-size: 0.9rem;
}
</style>
